<!--
* description: 领用退货入库
* author: chenweilin
* createdDate: 2021-7-16
-->

<template>
  <div class="app-container app-container-table" style="padding:0;">
    <one-table-template
      ref="multipleTable"
      :key="oneTableKey"
      :dynamic-buttons="tableButtons"
      :dynamic-components="tableComponents"
      :dynamic-api-config="apiConfig"
      :dynamic-table-cols="tableCols"
      :dynamic-form-fields="formField"
      :dynamic-is-show-select="true"
      :dynamic-is-init-table="false"
      :callback-obj="callbackObj"
    >
      <!--      address 地址码-->
      <template #addressCode="{row}">
        <el-input v-model="row.addressCode" clearable placeholder="请输入地址码"></el-input>
      </template>
      <!--      入库数量-->
      <template #inStoreQty="scope">
        <el-input-number
          :key="'sqty' + scope.$index"
          v-model="scope.row['inStoreQty']"
          :step="1"
          :min="1"
          :max="scope.row['canInStoreQty'] || 1000"
          step-strictly
          @change="inStoreQtyChange($event, scope.row)"
        />
      </template>
      <!--      入库异常数量-->
      <template #inStoreNonqty="scope">
        <el-input-number
          :key="'inStoreNonqty' + scope.$index"
          v-model="scope.row['inStoreNonqty']"
          :step="1"
          :min="0"
          disabled
          step-strictly
        />
      </template>
    </one-table-template>
  </div>
</template>
<script>

import { oneTableWithViewTemplateMixins } from '@/components/mixins/oneTableWithViewTemplateMixins'
import OneTableTemplate from '@/components/templates/oneTable'
import Vue from 'vue'
import api from '@/api/pa/apiBranchWarehouse'

export default {
  name: 'AcceptanceAndWarehousing',

  components: {
    OneTableTemplate
  },
  // 组件混入对象
  mixins: [oneTableWithViewTemplateMixins],

  // 阻塞路由预加载网格中组件的数据
  beforeRouteEnter(to, from, next) {
    Vue.prototype.$ConfigCache.CacheConfig.initData([to.path, ''], function() {
      next()
    })  
  },
  created(){
    console.log('--------------------reload--------------------')
  },
  data() {
    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path
    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode])

    return {
      selectData: [],
      placeDisabled: false,
      warehouseOptions: [],
      editRowData: {},
      options: [],
      // value: '',
      cacheData: {},
      // 网格查询API配置对象
      apiConfig: {
        APIUrl: '/mp/e3sh/spareparts/nodestorehouse/checkWarehousingService/queryCheckStorage.do'
      },
      // 动态组件-按钮
      tableButtons: [
        {
          compKey: 'btnKey1',
          type: 'primary',
          size: 'small',
          name: 'search',
          clickEvent: () => this.queryTable(1, '', '', '', (response) => {
            if (response.result === '1' && response.rows.length) {
              response.rows.forEach(row => {this.$set(row, 'placeDisabled', true)})
              this.$refs['multipleTable'].list = response.rows
            }
          }),
          text: this.$t('sys.button.query'), // 查询
          position: 'right',
          fuzzySearch: true
        },
        {
          compKey: 'comKey3',
          size: 'small',
          name: 'confirm',
          position: 'right',
          clickEvent: () => this.submit(),
          text: '提交',
          // disabled: true
        },
        {
          compKey: 'btnKey2',
          size: 'small',
          name: 'reset',
          clickEvent: () => this.reset(),
          text: this.$t('sys.button.reset'),
          position: 'right' // 重置
        }
      ],

      // 动态组件-查询条件
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents.length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
            .tableComponents
          : [
            {
              compKey: 'compKey2',
              labelName: '单据编号：',
              codeField: 'relateOrderCode',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: true,
              span:8
            },
            {
              compKey: 'compKey3',
              labelName: '出库日期：',
              codeField: 'relateOrderDateStart,relateOrderDateEnd',
              component: () => import('@/components/org/datePicker/datePicker.vue'),
              dateType: 'daterange',
              isMul: false,
              isMust: true,
              span:8
            }
          ],

      // 动态生成网格列
      tableCols:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          : [
            {
              prop: 'relateOrderCode',
              label: '网点内部领用出库单号',
              width: 140
            },
            {
              prop: 'relateOrderDate',
              label: '出库时间',
              width: 140
            },
            {
              prop: 'partNo',
              label: '备件编号',
              width: 140
            },
            {
              prop: 'partName',
              label: '备件名称',
              width: 140
            },
            {
              prop: 'unit',
              label: '备件单位',
              width: 140
            },
            {
              prop: 'inStoreQtySum',
              label: '已入库数量'
            },
            {
              prop: 'canInStoreQty',
              label: '可入库数量'
            },
            {
              prop: 'inStoreQty',
              label: '入库数量',
              isSlot: true,
              width: 150
            },
            {
              prop: 'addressCode',
              label: '备件地址码',
              isSlot: true,
              width: 150
            },
            {
              prop: 'inStoreNonqty',
              label: '入库异常数量',
              isSlot: true,
              width: 145
            },
            {
              prop: 'inStoreNonqtyReason',
              label: '入库异常原因',
              isComponent: true,
              comps: [
                {
                  compKey: 'compKey5' + this.$utils.generateId(),
                  codeField: 'inStoreNonqtyReason',
                  component: () => import('@/components/org/commonInput'),
                  type: 'inputText'
                }
              ],
              width: 140
            },
            {
              prop: 'receivePerson',
              label: '领用人',
              width: 140
            },
            {
              prop: 'custName',
              label: '申请人',
              width: 140
            },
            {
              prop: 'inStorePrice',
              label: '入库单价'
            },
            {
              prop: 'remark',
              label: '备注',
              isComponent: true,
              comps: [
                {
                  compKey: 'compKey5' + this.$utils.generateId(),
                  codeField: 'remark',
                  component: () => import('@/components/org/commonInput'),
                  type: 'inputText'
                }
              ],
              width: 140
            },
            
          ],

      // 表单查询数据
      formField: this.$utils.getFormField(this, {
        relateOrderCode: '',
        relateOrderDateStart: '',
        relateOrderDateEnd: '',
        warehouseName: '',
        billType:'IS005'

      }, this.$ConfigCache.CacheConfig.cacheData[viewPageCode]),

      callbackObj: {
        onCheckSelectChange: selection => {
          this.selectData = selection
          // this.handleSelectionChange(selection)
        }
      }
    }
  },
  watch: {
    'formField.billType': {
      handler(val) {
        if (val) {
          this.queryTable()
        }
      }
    }
  },
  mounted() {
    // 列表查询
    this.queryTable(1, '', '', '', (response) => {
      if (response.result === '1' && response.rows.length) {
        response.rows.forEach(row => {this.$set(row, 'placeDisabled', true)})
        this.$refs['multipleTable'].list = response.rows
      }
    })
    // 查询仓库下拉框数据
    this.loadwarehouseData()
  },
  methods: {
    // 入库数量改变
    inStoreQtyChange(val, row) {
      // 计算异常入库数量
      console.log(val)
      this.$set(row, 'inStoreNonqty', row['canInStoreQty'] - Number(val))
      // row['inStoreAmount'] = (Number(val) * Number(row['inStorePrice'])).toFixed(2)
    },
    // 仓位下拉框打开
    placeVisibleChange(isOpen, scope) {
      if (!isOpen) return
      this.warevisibleEvent(isOpen, scope)
    },
    warevisibleEvent(isOpen, scope) {
      if (!isOpen) return
      if (scope.row['warehouseId'] + scope.row['partId'] in this.cacheData) return
      if (!scope.row['warehouseId']) return
      this.$requestAPI({
        // apiUrl: '/mp/e3sh/spareparts/nodestorehouse/checkWarehousingService/queryWarehouseCode.do',
        apiUrl: 'mp/e3sh/spareparts/nodestorehouse/dlrPartWarehouseMaintainService/queryDlrPartWareSpaceInfo.do',
        variables: {
          warehouseId: scope.row['warehouseId'],
          partId: scope.row['partId']
        }
      }).then(res => {
        if (res.result === '1') {
          // this.cacheData[scope.row['warehouseId'] + scope.row['partId']] = res.rows
          this.$set(this.cacheData, scope.row['warehouseId'] + scope.row['partId'], res.rows)
        } else {
          this.$message(res.msg ? res.msg : '')
        }
      }).catch(err => {
        if (err.response.data.msg) {
          this.$message(err.response.data.msg)
        } else {
          this.$message(err.message)
        }
      })
    },
    // 加载仓库数据
    loadwarehouseData() {
      this.$requestAPI({
        apiUrl: '/mp/e3sh/spareparts/nodestorehouse/checkWarehousingService/queryWarehouseName.do',
        variables: {}
      }).then(res => {
        if (res.result === '1') {
          this.warehouseOptions = res.rows
        } else {
          this.$message(res.msg ? res.msg : '')
        }
      }).catch(err => {
        if (err.response.data.msg) {
          this.$message(err.response.data.msg)
        } else {
          this.$message(err.message)
        }
      })
    },
    wareHouseChange(val, scope) {
      scope.row['placeDisabled'] = !val
      const opt = this.warehouseOptions.find(o => o.warehouseId === val)
      scope.row['warehouseCode'] = opt.warehouseCode
      scope.row['warehouseName'] = opt.warehouseName
      if (val + scope.row['partId'] in this.cacheData) return
      this.$nextTick(() => {
        this.$set(scope.row, 'placeCode', '')
        // this.$set(scope.row, 'storageLocation', '')
      })
      this.$requestAPI({
        // apiUrl: '/mp/e3sh/spareparts/nodestorehouse/checkWarehousingService/queryWarehouseCode.do',
        apiUrl: 'mp/e3sh/spareparts/nodestorehouse/dlrPartWarehouseMaintainService/queryDlrPartWareSpaceInfo.do',
        variables: {
          warehouseId: val,
          partId: scope.row['partId']
        }
      }).then(res => {
        if (res.result === '1') {
          // this.cacheData[val + scope.row['partId']] = res.rows
          this.$set(this.cacheData, val + scope.row['partId'], res.rows)
        } else {
          this.$message(res.msg ? res.msg : '')
        }
      }).catch(err => {
        if (err.response.data.msg) {
          this.$message(err.response.data.msg)
        } else {
          this.$message(err.message)
        }
      })
    },
    changeSelect(val, scope) {
      // eslint-disable-next-line no-return-assign
      // this.$set(scope.row, 'storageId', val)
      // scope.row['storageLocation'] = this.cacheData[scope.row.warehouseId + scope.row.partId].find(o => o['storageId'] === val)['storageLocation']
    },
    // visibleEvent(a, b) {
    //   if (this.cacheData.hasOwnProperty(b.row.partId)) {
    //   } else {
    //     this.$requestAPI({
    //       apiUrl: api.queryWarehouseCode.APIUrl,
    //       variables: { partId: b.row.partId }
    //     }).then((response) => {
    //       if (response.result === '1') {
    //         // this.cacheData[b.row.partId] = response.rows
    //         this.$set(this.cacheData, b.row.partId, response.rows)
    //       }
    //     })
    //   }
    // },
    submit() {
      if (!this.selectData.length) return this.$message('请至少选择一条数据!')
      // let isValid = true
      // this.selectData.every(row => {
      //   if (!row['addressCode']) {
      //     isValid = false
      //     return false
      //   }
      //   return true
      // })
      // if (!isValid) return this.$message('表格中[ 地址码 ]为必选！')
      this.$confirm('确定要提交吗?', '提示', {
        type: 'warning'
      }).then(() => {
        const queryObj = {
        // 保存需要传 type="mutation"
          type: 'mutation',
          apiConfig: api.updateSubmit,
          // 条件/实体参数（变量），根据typeParam中的定义配置
          variables: {
            dataInfo: this.selectData
          }
        }
        // 转换了中台请求格式数据
        var paramD = this.$getParams(queryObj)
        this.$requestAPI(paramD).then((response) => {
          if (response.result === '1') {
            this.$message({
              message: response.msg,
              duration: 1000
            })
            this.selectData = []
            this.queryTable(1)
          } else {
            this.$message({
              message: response.msg,
              duration: 1000
            })
          }
          // this.queryTable(1)
        })
      })
    },

    // 当选择项发生变化时会触发该事件
    handleSelectionChange(selection) {
      const btns = this.tableButtons.filter(o => o.disabled !== undefined)
      if (btns.length > 0) {
        const isCheck = selection && selection.length > 0
        btns.forEach((item) => {
          item.disabled = !isCheck
        })
      }
    }
  }
}
</script>
